﻿    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tank : MonoBehaviour {

	private int _type;  // 坦克类型，0~3敌人，4~6玩家一，7~9玩家二
	public int Type{   
		get{
			return _type;
		}
		set{ 
			_type = value;

			Blood = Config.tankConfig.Blood [_type];
			Speed = Config.tankConfig.Speed [_type];
			AttackInterval = Config.tankConfig.AttackInterval [_type]; 

			AdjustColor ();
		}
	}

	private bool _withFood = false;  // 是否带着食物
	public bool WithFood {
		get{ 
			return _withFood;
		}
		set{
			if (Type < 4) {
				_withFood = value;
				if (_withFood == false) {
					Type = _type;  // 自动改变颜色
				} else {
					Utils.ChangeColor (gameObject, Color.red);
				}
			} 
		}
	}

	private GameObject ring = null;

	private bool _canKill;
	public bool CanKill{
		get{ 
			return _canKill;
		}
		set{ 
			_canKill = value;
			if (_canKill == false) {  // 无敌效果开始
				InvincibleTimer = Config.foodConfig.EffectivenessDuration[(int)Food.FoodType.INVINCIBLE];
				if (ring == null) {
					ring = _gameController.Create ("ring", gameObject.transform.position);
				}

			}
		}
	}

	public int Blood;
	public float Speed;
	private int _direction = 0;   // 坦克朝向

	private void AdjustDirection(int direction){  // 调整方向

		if (this._direction == direction){
		} else if (this._direction == (direction + 3) % 4) {
			this._direction = direction;
			gameObject.transform.Rotate (0, 0, 90);
		} else if (this._direction == (direction + 1) % 4) {
			this._direction = direction;
			gameObject.transform.Rotate (0, 0, -90);
		} else {
			this._direction = direction;
			gameObject.transform.Rotate (0, 0, 180);
		}

	}

	public void Copy(Tank tank){
		this.CanKill = tank.CanKill;
		this.InvincibleTimer = tank.InvincibleTimer;
		this._direction = tank._direction;
	}
		
	void OnCollisionEnter(Collision otherObj){
		SlideStatus = false;
		if (Type < 4) {
			if (_hit == true)
				return;
			_hit = true;
			AdjustDirection ((_direction + 2) % 4);
			gameObject.transform.Translate (0.5f * Time.deltaTime, 0, 0);
		}
	}

	/**
	 * 是否已经处理碰撞事件，每帧置为false。
	 * 原因：一帧不能处理两次碰撞事件。
	 */
	private bool _hit = false;   
	void OnCollisionExit(Collision otherObj){
		
		if (Type < 4) {
			AdjustDirection ( Random.Range(0, 4) );
		}
	}

	public bool SlideStatus = false;

	void OnTriggerEnter(Collider otherObj){        // 与其他物体碰撞触发
		string otherTag = otherObj.gameObject.tag;
		if (Type >= 4 && otherTag.Equals ("food")) {
			Food food = otherObj.gameObject.GetComponent<Food> ();
			switch (food.Type) {
			case Food.FoodType.INVINCIBLE:  // 无敌
				_gameController.ChangeInvincible (gameObject, otherObj.gameObject);
				break;
			case Food.FoodType.BOMB:  		// 炸弹
				_gameController.BombBurst (gameObject, otherObj.gameObject);
				break;
			case Food.FoodType.IRON: 		// 铁墙
				_gameController.UpgradeBaseDefense (gameObject, otherObj.gameObject);
				break;
			case Food.FoodType.LEVEL: 		// 升级
				_gameController.Upgrade (gameObject, otherObj.gameObject);
				break;
			case Food.FoodType.LIFE:  		// 生命
				_gameController.PlusLife (gameObject, otherObj.gameObject);
				break;
			case Food.FoodType.HALT:  		// 暂停
				_gameController.HaltEnemy (gameObject, otherObj.gameObject);
				break;
			}
		} else if (Type >= 4 && otherTag.Equals ("slide")) {
			if (SlideStatus == false) { 
				SlideStatus = true;
				StartCoroutine ("Slide");
			}
		} 
	}
		
	private void Attack(){
		if (_type >= 4 && _attackTimer > 0) {
			return;
		}
		_attackTimer = AttackInterval;
		GameObject bullet = Instantiate ( Resources.Load<GameObject>(@"prefabs\bullet") );
		if(_type >= 4) bullet.GetComponent<AudioSource> ().enabled = true;

		Bullet bulletComponent = bullet.GetComponent<Bullet> ();
		bulletComponent.Type = Type;
		bullet.GetComponent<Bullet> ().init (_direction);

		bullet.transform.position = gameObject.transform.position;
	}

	private void AI(){
		// 移动 AI
		if (Type != 1) {
			gameObject.transform.Translate (Speed  * Time.deltaTime, 0, 0);
		}
		else {
			if (Random.Range (0, 100) == 0) {
				int direction = Random.Range (0, 4);
				AdjustDirection (direction);
			}
			gameObject.transform.Translate (Speed  * Time.deltaTime, 0, 0);
		}

		// 攻击 AI
		int rd = Random.Range (0, 2*Mathf.FloorToInt(AttackInterval*50));
		if (rd == 0) {
			Attack ();
		}
	}
		
	IEnumerator Slide() {
		while(SlideStatus) {
			gameObject.transform.Translate (Config.foodConfig.SlideSpeed * Time.deltaTime, 0, 0);
			yield return null;
		}
	}

	private void Move(){

		int flag = 0;
		if (Type < 7) {
			if (Input.GetKey (KeyCode.A)) {
				flag |= 1;
				AdjustDirection (3);
			} else if (Input.GetKey (KeyCode.D)) {
				flag |= 1;
				AdjustDirection (1);
			} else if (Input.GetKey (KeyCode.W)) {
				flag |= 1;
				AdjustDirection (0);
			} else if (Input.GetKey (KeyCode.S)) {
				flag |= 1;
				AdjustDirection (2);
			} 

			if (Input.GetKey (KeyCode.Z)) {
				StartCoroutine ("Slide");
			}

			if (Input.GetKey (KeyCode.J)) {
				flag |= 2;
			}
		} else {
			if (Input.GetKey (KeyCode.LeftArrow)) {
				flag |= 1;
				AdjustDirection (3);
			} else if (Input.GetKey (KeyCode.RightArrow)) {
				flag |= 1;
				AdjustDirection (1);
			} else if (Input.GetKey (KeyCode.UpArrow)) {
				flag |= 1;
				AdjustDirection (0);
			} else if (Input.GetKey (KeyCode.DownArrow)) {
				flag |= 1;
				AdjustDirection (2);
			} 

			if (Input.GetKey (KeyCode.Keypad2)) {
				flag |= 2;
			}
		}
		if (HaltTimer <= 0 && (flag & 1) > 0) {  //需要移动
			if (SlideStatus == true) {
				
			} else {
				gameObject.transform.Translate (Speed * Time.deltaTime, 0, 0);
			}
		}
		if ((flag & 2) > 0) {  // 发出子弹
			Attack ();
		}
	}

	public void BeingAttacked(int owner, int attackLevel){
		if (CanKill == false)
			return;
		if (WithFood == true) {
			_gameController.GenFood ();
			WithFood = false;
			return;
		}
		if (_type < 4) {  // 敌方坦克被攻击
			Blood -= attackLevel;
			if (Blood <= 0) {
				_gameController.AddScore (owner-1, gameObject);
				_gameController.Clear (gameObject);
			} else {
			
			}
		} else if (_type < 7) {  // 玩家一 被攻击
			if (owner == 0) {  // 被敌人攻击
				_gameController.Degrade(gameObject);
				//_gameController.Clear (gameObject);
			} else {  // 被友方攻击
				HaltTimer = Config.gameConfig.FriendlyAttackPenaltyTime;
			}
		} else {  // 玩家二 被攻击
			if (owner == 0) {  // 被敌人攻击
				_gameController.Degrade(gameObject);
				//_gameController.Clear(gameObject);
			} else {  // 被友方攻击
				HaltTimer = Config.gameConfig.FriendlyAttackPenaltyTime;
			}
		}

		AdjustColor ();
	}

	private void AdjustColor(){
		if (_type >= 4)
			return;
		else if (_type == 3) {
			if (Blood == 4) {
				Utils.ChangeColor (gameObject, Utils.GetColor("#548C00"));
			} else if (Blood == 3) {
				Utils.ChangeColor (gameObject, Utils.GetColor("#5CADAD"));
			} else if (Blood == 2) {
				Utils.ChangeColor (gameObject, Utils.GetColor("#FFE66F"));
			} else {
				Utils.ChangeColor (gameObject, Color.gray);
			}
		} else if (_type == 2 && Blood == 2) {
			Utils.ChangeColor (gameObject, Utils.GetColor("#FFE66F"));
		} else {
			Utils.ChangeColor (gameObject, Color.gray);
		}
	}

	private GameController _gameController;

	void Awake() {
		_gameController = GameController.GetInstance ();
	}

	void Start() {
		

		//CanKill = false;  // 出生有无敌效果
		InvincibleTimer = Config.gameConfig.InvincibleTimeOfBirth; 
		HaltTimer = 0;
	}

	public float AttackInterval; 			   // 攻击间隔
	public float _attackTimer;                 // 攻击间隔计数，当其大于0 时不可攻击	
	public float InvincibleTimer;              // 无敌计时器
	public float HaltTimer;                    // 暂停时间，专用于玩家被友方攻击，暂停期间不能移动，且闪烁
	private int _flickerTimer = 0;             // 用于控制物体闪烁

	void FixedUpdate() {
		_hit = false;
	}

	void Update() {
		if (_gameController.Status>0 && Time.timeScale!=0) {

			if (_type < 4) {  // 敌方
				if(_gameController.Status == 1) AI ();
			} else {			
				Move ();
				if (_attackTimer > 0) {
					_attackTimer -= Time.deltaTime;
				}
			}

			if (CanKill == false) {
				InvincibleTimer-=Time.deltaTime;
				if (InvincibleTimer <= 0) {  // 无敌效果结束

					_gameController.Clear (ring);
					ring = null;

					CanKill = true;
				}
			}

			if (HaltTimer > 0) {
				HaltTimer-=Time.deltaTime;
				_flickerTimer++;
				if (_flickerTimer % Config.gameConfig.FlickerTimer == 0) {
					Utils.ChangeHide (gameObject);
				}
				if (HaltTimer <= 0) {
					Utils.ChangeHide (gameObject, true);
					_flickerTimer = 0;
				}
			}

			if (ring != null) {
				ring.transform.position = gameObject.transform.position;
			}
		}
	}
		
	public void Clear() {
		if (ring != null) {
			_gameController.Clear (ring);
			ring = null;
		}
	}
}
